using System;
using UnityEngine;
using Pumpkin.Utils;

namespace Pumpkin.FrameBase
{
    public class SceneManager : Singleton<SceneManager>
    {
        private object[] param1 = new object [1];
        private Action clearup;
        private CrossDomainInstance crossSceneMgr;
        private IFrameModule module_;

        public SceneManager()
        {
            UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
            crossSceneMgr = CrossInstanceFactory.Instance.CreateWithInstantial(BaseCrossType.SceneManager);
			crossSceneMgr.Invoke("SetInstance", this);
        }

        public void AddClearupAction(Action action)
        {
            clearup += action;
        }  

        public void Init()
        {
            if(HotFixConfigs.SceneResMgrFile == null || !GlobalConfigs.Instance.HotFixEnabled())
            {
                return;
            }

            ResHelper.PreLoadCommonRes();
        }

        public void LoadScene(string sceneName, bool isLoadingScene = false)
        {
            if(!isLoadingScene && GlobalConfigs.Instance.HotFixEnabled())
            {
                ResHelper.PreLoadSceneRes(sceneName);
            }
            if(clearup != null)
            {
                clearup.Invoke();
            }

            UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
        }

        public AsyncOperation LoadSceneAsync(string sceneName, bool isLoadingScene = false)
        {
            //虽然场景是异步加载，但这里场景相关的AB包依然使用同步加载模型
            if(!isLoadingScene && GlobalConfigs.Instance.HotFixEnabled())
            {
                ResHelper.PreLoadSceneRes(sceneName);
            }
            if(clearup != null)
            {
                clearup.Invoke();
            }

            return UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneName);
        }

        public void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode)
        {
            Log.LogDebug(scene.name + " loaded");
            param1[0] = scene.name;
            crossSceneMgr.Invoke("OnSceneLoaded", param1);
        }

        public void OnUIRootLoaded(UnityEngine.SceneManagement.Scene scene)
        {
            param1[0] = scene.name;
            crossSceneMgr.Invoke("OnUIRootLoaded", param1); 
        }
    }
}